package com.excu.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * 加密HTTP客户端
 * 用于发送加密的JSON参数POST请求
 */
public class EncryptedHttpClient {
    private final String secretKey;
    // 连接超时时间(毫秒)
    private static final int CONNECT_TIMEOUT = 5000;
    // 读取超时时间(毫秒)
    private static final int READ_TIMEOUT = 5000;
    
    /**
     * 构造方法
     * @param secretKey 加密密钥
     */
    public EncryptedHttpClient(String secretKey) {
        // 验证密钥
        EncryptionUtils.validateKeyLength(secretKey);
        this.secretKey = secretKey;
    }
    
    /**
     * 发送加密的POST请求
     * @param url 请求地址
     * @param jsonParam 原始JSON参数
     * @return 服务器响应
     * @throws Exception 可能的异常
     */
    public String sendEncryptedPost(String url, String jsonParam) throws Exception {
        if (url == null || url.isEmpty()) {
            throw new IllegalArgumentException("请求URL不能为空");
        }
        
        // 加密参数
        String encryptedData = EncryptionUtils.encrypt(jsonParam, secretKey);
        
        // 构建发送的数据格式: {"data":"加密后的字符串"}
        String requestBody = "{\"data\":\"" + escapeJson(encryptedData) + "\"}";
        
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        OutputStream os = null;
        
        try {
            URL requestUrl = new URL(url);
            connection = (HttpURLConnection) requestUrl.openConnection();
            
            // 设置请求属性
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            connection.setConnectTimeout(CONNECT_TIMEOUT);
            connection.setReadTimeout(READ_TIMEOUT);
            
            // 发送数据
            os = connection.getOutputStream();
            os.write(requestBody.getBytes(StandardCharsets.UTF_8));
            os.flush();
            
            // 读取响应
            int responseCode = connection.getResponseCode();
            if (responseCode >= 200 && responseCode < 300) {
                reader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
            } else {
                reader = new BufferedReader(
                    new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8));
            }
            
            // 构建响应字符串
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            
            return response.toString();
            
        } finally {
            // 关闭资源
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    // 忽略关闭异常
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    // 忽略关闭异常
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
    
    /**
     * 转义JSON中的特殊字符
     * @param value 要转义的字符串
     * @return 转义后的字符串
     */
    private String escapeJson(String value) {
        if (value == null) {
            return "";
        }
        return value.replace("\\", "\\\\")
                   .replace("\"", "\\\"")
                   .replace("\b", "\\b")
                   .replace("\f", "\\f")
                   .replace("\n", "\\n")
                   .replace("\r", "\\r")
                   .replace("\t", "\\t");
    }
}
    